<template>
  <div class="exam-result-page">
    <div class="page-header">
      <h2>考试结果</h2>
      <p>查看您的考试成绩和详细分析</p>
    </div>

    <!-- 成绩概览 -->
    <div class="result-overview">
      <div class="overview-card">
        <div class="score-display">
          <div class="score-circle">
            <div class="score-number">{{ examResult.examTotalScore }}</div>
            <div class="score-label">总分</div>
          </div>
          <div class="result-badge" :class="getResultClass(examResult.passed)">
            {{ examResult.passed == '1'? '通过': '未通过' }}
          </div>
        </div>
        
        <div class="result-details">
          <div class="detail-item">
            <span class="label">考试名称：</span>
            <span class="value">{{ examResult.examName }}</span>
          </div>
          <div class="detail-item">
            <span class="label">考试时间：</span>
            <span class="value">{{ formatDateTime(examResult.startedAt) }} - {{ formatDateTime(examResult.finishedAt) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">用时：</span>
            <span class="value">{{ examResult.durationSec }}分钟</span>
          </div>
          <div class="detail-item">
            <span class="label">及格分数：</span>
            <span class="value">{{ examResult.examPassScore }}分</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 成绩分析 -->
    <div class="analysis-section">
      <div class="section-header">
        <h3>成绩分析</h3>
      </div>
      
      <div class="analysis-grid">
        <div class="analysis-card">
          <h4>答题统计</h4>
          <div class="stats-content">
            <div class="stat-row">
              <span class="stat-label">总题数：</span>
              <span class="stat-value">{{ analysis.totalQuestions }}</span>
            </div>
            <div class="stat-row">
              <span class="stat-label">正确题数：</span>
              <span class="stat-value success">{{ analysis.passedQuestions }}</span>
            </div>
            <div class="stat-row">
              <span class="stat-label">错误题数：</span>
              <span class="stat-value danger">{{ analysis.wrongQuestions }}</span>
            </div>
            <div class="stat-row">
              <span class="stat-label">正确率：</span>
              <span class="stat-value">{{ analysis.passingRate }}%</span>
            </div>
          </div>
        </div>
        <!---->
        <!--<div class="analysis-card">-->
          <!--<h4>时间效率</h4>-->
          <!--<div class="time-efficiency">-->
            <!--<div class="efficiency-score">{{ analysis.timeEfficiency }}%</div>-->
            <!--<div class="efficiency-label">时间利用效率</div>-->
            <!--<el-progress -->
              <!--:percentage="analysis.timeEfficiency" -->
              <!--:color="getEfficiencyColor(analysis.timeEfficiency)"-->
            <!--/>-->
          <!--</div>-->
        <!--</div>-->
        
        <!--<div class="analysis-card">-->
          <!--<h4>薄弱环节</h4>-->
          <!--<div class="weak-areas">-->
            <!--<div v-for="area in analysis.weakAreas" :key="area" class="weak-area-item">-->
              <!--<el-tag type="warning" size="small">{{ area }}</el-tag>-->
            <!--</div>-->
          <!--</div>-->
        <!--</div>-->
      </div>
    </div>

    <!-- 学习建议 -->
    <!--<div class="suggestions-section">-->
      <!--<div class="section-header">-->
        <!--<h3>学习建议</h3>-->
      <!--</div>-->
      <!---->
      <!--<div class="suggestions-content">-->
        <!--<div v-for="(suggestion, index) in analysis.suggestions" :key="index" class="suggestion-item">-->
          <!--&lt;!&ndash;<div class="suggestion-icon">&ndash;&gt;-->
            <!--&lt;!&ndash;<el-icon><Lightbulb /></el-icon>&ndash;&gt;-->
          <!--&lt;!&ndash;</div>&ndash;&gt;-->
          <!--<div class="suggestion-text">{{ suggestion }}</div>-->
        <!--</div>-->
      <!--</div>-->
    <!--</div>-->

    <!-- 答题回顾 -->
    <div class="review-section">
      <div class="section-header">
        <h3>答题回顾</h3>
        <div class="filter-controls">
          <el-select v-model="reviewFilter" placeholder="筛选题目" style="width: 120px;">
            <el-option label="全部" value="all" />
            <el-option label="正确" value="correct" />
            <el-option label="错误" value="wrong" />
          </el-select>
        </div>
      </div>
      
      <div class="review-content">
        <div v-for="(answer, index) in filteredAnswers" :key="index" class="answer-item">
          <div class="answer-header">
            <span class="question-number">第 {{ index + 1 }} 题</span>
            <span class="question-type">{{ getQuestionTypeText(answer.type) }}</span>
            <span class="answer-result" :class="getAnswerResultClass(answer.isCorrect)">
              {{ answer.isCorrect ? '正确' : '错误' }}
            </span>
            <span class="answer-score">{{ answer.score }}分</span>
          </div>
          
          <div class="question-content">
            <p>{{ answer.content }}</p>
          </div>
          
          <div class="answer-details">
            <div class="answer-row">
              <span class="label">您的答案：</span>
              <span class="value" :class="getAnswerClass(answer.isCorrect)">
                {{ formatAnswer(answer.userAnswer, answer.questionType) }}
              </span>
            </div>
            <div class="answer-row">
              <span class="label">正确答案：</span>
              <span class="value correct">{{ formatAnswer(answer.answer, answer.questionType) }}</span>
            </div>
            <div v-if="answer.explanation" class="answer-row">
              <span class="label">解析：</span>
              <span class="value explanation">{{ answer.remark }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-section">
      <div class="action-buttons">
        <!--<el-button type="primary" size="large" @click="retakeExam">-->
          <!--重新考试-->
        <!--</el-button>-->
        <el-button type="success" size="large" @click="viewWrongQuestions">
          查看错题集
        </el-button>
        <el-button type="info" size="large" @click="backToExams">
          返回考试列表
        </el-button>
        <!--<el-button type="warning" size="large" @click="downloadReport">-->
          <!--下载报告-->
        <!--</el-button>-->
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
//import { Lightbulb } from '@element-plus/icons-vue'
import { getExamResult,statsQuestion } from '@/api/system'

const router = useRouter()
const route = useRoute()

// 响应式数据
const examResult = ref({})
const analysis = ref({})
const answers = ref([])
const reviewFilter = ref('all')
const loading = ref(false)
const msgId = ref('')


// 计算属性
const filteredAnswers = computed(() => {
  if (reviewFilter.value === 'all') {
    return answers.value
  }
  return answers.value.filter(answer => {
    if (reviewFilter.value === 'correct') return answer.isCorrect
    if (reviewFilter.value === 'wrong') return !answer.isCorrect
    return true
  })
})

// 获取考试结果
const fetchExamResult = async () => {
//  const resultId = route.query.resultId
  msgId.value = route.query.resultId
//  const score = route.query.score
//  const totalQuestions = route.query.totalQuestions
//  const correctAnswers = route.query.correctAnswers
  
//  if (!resultId) {
//    ElMessage.error('缺少考试结果ID')
//    router.push('/exams')
//    return
//  }

  loading.value = true
  try {
//    // 使用mock数据
//    const mockExamResult = {
//      id: resultId,
//      examId: examId || 'exam_001',
//      examName: '日语N5基础语法考试',
//      examDate: new Date().toISOString(),
//      score: parseInt(score) || 85,
//      totalScore: 100,
//      totalQuestions: parseInt(totalQuestions) || 50,
//      correctAnswers: parseInt(correctAnswers) || 42,
//      wrongAnswers: (parseInt(totalQuestions) || 50) - (parseInt(correctAnswers) || 42),
//      duration: 45,
//      status: parseInt(score) >= 60 ? '通过' : '未通过',
//      passScore: 60
//    }
//
    const mockAnalysis = {
      overall:  '及格',
      strengths: ['语法基础扎实', '词汇量丰富', '理解能力强'],
      weaknesses: ['听力理解需要加强', '写作表达有待提高'],
//      suggestions: [
//        '建议多听日语原声材料，提高听力理解能力',
//        '可以多练习写作，提高表达能力',
//        '建议复习错题，巩固薄弱环节',
//        '可以参加更多模拟考试，熟悉考试节奏'
//      ]
    }
//
    const mockAnswers = [
      {
        questionId: 'q1',
        questionType: 'singleChoice',
        questionContent: '「は」和「が」的区别是什么？',
        userAnswer: 'A',
        correctAnswer: 'A',
        isCorrect: true,
        score: 2,
        explanation: '「は」用于提示主题，表示要谈论的话题；「が」用于表示动作的主体或状态的主体。'
      },
      {
        questionId: 'q2',
        questionType: 'singleChoice',
        questionContent: '在商务场合，如何礼貌地拒绝邀请？',
        userAnswer: 'A',
        correctAnswer: 'B',
        isCorrect: false,
        score: 0,
        explanation: '在商务场合，应该使用敬语表达歉意，并说明无法参加的原因。'
      },
      {
        questionId: 'q3',
        questionType: 'singleChoice',
        questionContent: '听力材料中提到的会议时间是？',
        userAnswer: 'A',
        correctAnswer: 'B',
        isCorrect: false,
        score: 0,
        explanation: '听力材料中明确提到了「午後2時」这个时间。'
      },
      {
        questionId: 'q4',
        questionType: 'singleChoice',
        questionContent: '文章的主要观点是什么？',
        userAnswer: 'B',
        correctAnswer: 'B',
        isCorrect: true,
        score: 2,
        explanation: '文章通过多个例子说明了环保意识在现代社会中的重要性。'
      },
      {
        questionId: 'q5',
        questionType: 'multipleChoice',
        questionContent: '以下哪些是日语的基本敬语？',
        userAnswer: ['A', 'B'],
        correctAnswer: ['A', 'B', 'C'],
        isCorrect: false,
        score: 1,
        explanation: 'です、ます、ございます是日语中最基本的敬语形式，用于表示礼貌。'
      }
    ]
//
//    examResult.value = mockExamResult
//    analysis.value = mockAnalysis
//    answers.value = mockAnswers

    const resp = await getExamResult(msgId.value)
    examResult.value = resp?.data?.examRecordsEntity
    answers.value = resp?.data?.recordDetailEntities

    const res = await statsQuestion({recordId : msgId.value})
    analysis.value = res?.data

  } catch (error) {
    console.error('获取考试结果失败:', error)
    ElMessage.error('获取考试结果失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取结果样式类
const getResultClass = (result) => {
  return result === '通过' ? 'success' : 'danger'
}

// 获取答题结果样式类
const getAnswerResultClass = (isCorrect) => {
  return isCorrect ? 'correct' : 'wrong'
}

// 获取答案样式类
const getAnswerClass = (isCorrect) => {
  return isCorrect ? 'correct' : 'wrong'
}

// 获取题目类型文本
const getQuestionTypeText = (type) => {
  const typeMap = {
    'singleChoice': '单选题',
    'multipleChoice': '多选题',
    'trueFalse': '判断题',
    'fillBlank': '填空题'
  }
  return typeMap[type] || '单选题'
}

// 格式化答案
const formatAnswer = (answer, type) => {
  if (type === 'multipleChoice' && Array.isArray(answer)) {
    return answer.join(', ')
  }
  return answer || '未作答'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN')
}

// 获取效率颜色
const getEfficiencyColor = (efficiency) => {
  if (efficiency >= 80) return '#67C23A'
  if (efficiency >= 60) return '#E6A23C'
  return '#F56C6C'
}

// 重新考试
const retakeExam = () => {
  router.push(`/exams`)
}

// 查看错题集
const viewWrongQuestions = () => {
  router.push('/wrong-questions')
}

// 返回考试列表
const backToExams = () => {
  router.push('/exams')
}

// 下载报告
const downloadReport = () => {
  ElMessage.success('报告下载功能开发中')
}

onMounted(() => {
  fetchExamResult()
})
</script>

<style scoped>
.exam-result-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px 0;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h2 {
  color: #2c3e50;
  margin: 0 0 10px 0;
  font-size: 2rem;
}

.page-header p {
  color: #666;
  margin: 0;
  font-size: 1.1rem;
}

.result-overview {
  max-width: 1200px;
  margin: 0 auto 40px;
  padding: 0 20px;
}

.overview-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 40px;
}

.score-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.score-circle {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  background: linear-gradient(135deg, #409EFF, #67C23A);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
}

.score-number {
  font-size: 2.5rem;
  font-weight: bold;
  margin-bottom: 5px;
}

.score-label {
  font-size: 1rem;
}

.result-badge {
  padding: 8px 20px;
  border-radius: 20px;
  font-weight: bold;
  font-size: 1.1rem;
}

.result-badge.success {
  background: #f0f9ff;
  color: #67C23A;
}

.result-badge.danger {
  background: #fef0f0;
  color: #F56C6C;
}

.result-details {
  flex: 1;
}

.detail-item {
  display: flex;
  margin-bottom: 15px;
  font-size: 1rem;
}

.detail-item .label {
  width: 100px;
  color: #666;
  font-weight: 500;
}

.detail-item .value {
  color: #2c3e50;
  font-weight: 500;
}

.analysis-section {
  max-width: 1200px;
  margin: 0 auto 40px;
  padding: 0 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.section-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.5rem;
}

.analysis-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 25px;
}

.analysis-card {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.analysis-card h4 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 1.2rem;
}

.stats-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.stat-row:last-child {
  border-bottom: none;
}

.stat-label {
  color: #666;
}

.stat-value {
  font-weight: bold;
  color: #2c3e50;
}

.stat-value.success {
  color: #67C23A;
}

.stat-value.danger {
  color: #F56C6C;
}

.time-efficiency {
  text-align: center;
}

.efficiency-score {
  font-size: 2rem;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 10px;
}

.efficiency-label {
  color: #666;
  margin-bottom: 20px;
}

.weak-areas {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.weak-area-item {
  margin-bottom: 10px;
}

.suggestions-section {
  max-width: 1200px;
  margin: 0 auto 40px;
  padding: 0 20px;
}

.suggestions-content {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.suggestion-item {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.suggestion-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.suggestion-icon {
  color: #E6A23C;
  font-size: 1.2rem;
  margin-top: 2px;
}

.suggestion-text {
  color: #2c3e50;
  line-height: 1.6;
  flex: 1;
}

.review-section {
  max-width: 1200px;
  margin: 0 auto 40px;
  padding: 0 20px;
}

.review-content {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.answer-item {
  margin-bottom: 30px;
  padding-bottom: 30px;
  border-bottom: 1px solid #eee;
}

.answer-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.answer-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.question-number {
  font-weight: bold;
  color: #409EFF;
}

.question-type {
  background: #f0f9ff;
  color: #409EFF;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.8rem;
}

.answer-result {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: bold;
}

.answer-result.correct {
  background: #f0f9ff;
  color: #67C23A;
}

.answer-result.wrong {
  background: #fef0f0;
  color: #F56C6C;
}

.answer-score {
  background: #f0f9ff;
  color: #67C23A;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: bold;
}

.question-content {
  margin-bottom: 20px;
}

.question-content p {
  margin: 0;
  color: #2c3e50;
  line-height: 1.6;
  font-size: 1rem;
}

.answer-details {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
}

.answer-row {
  display: flex;
  margin-bottom: 15px;
}

.answer-row:last-child {
  margin-bottom: 0;
}

.answer-row .label {
  width: 100px;
  color: #666;
  font-weight: 500;
}

.answer-row .value {
  flex: 1;
  color: #2c3e50;
}

.answer-row .value.correct {
  color: #67C23A;
  font-weight: bold;
}

.answer-row .value.wrong {
  color: #F56C6C;
  font-weight: bold;
}

.answer-row .value.explanation {
  color: #666;
  font-style: italic;
}

.action-section {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  text-align: center;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  flex-wrap: wrap;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .overview-card {
    flex-direction: column;
    text-align: center;
  }
  
  .analysis-grid {
    grid-template-columns: 1fr;
  }
  
  .answer-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 15px;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
}
</style>
